# -*- coding: utf-8 -*-
import os
import json
import csv


def load_json_file(json_file):
    if not os.path.exists(json_file):
        raise FileNotFoundError()
    with open(json_file, 'r', encoding='utf-8') as f:
        json_data = json.load(f)
    return json_data


def dump_json_file(json_data, json_file):
    assert isinstance(json_data, dict)
    with open(json_file, 'w') as f:
        json.dump(json_data, f, indent=4, ensure_ascii=False)


def load_csv_file(csv_file):
    if not os.path.exists(csv_file):
        raise FileNotFoundError()

    out_result = []
    with open(csv_file, 'r', encoding='utf-8') as f:
        reader = csv.reader(f)
        fieldnames = next(reader)
        csv_reader = csv.DictReader(f, fieldnames=fieldnames)
        for row in csv_reader:
            out_dict = {}
            for key, value in row.items():
                out_dict[key] = value
            out_result.append(out_dict)
    return out_result


def dump_csv_file(csv_data, csv_file):
    assert isinstance(csv_data, list)
    with open(csv_file, 'w') as f:
        writer = csv.writer(f)
        fieldnames = csv_data.pop(0)
        writer.writerow(fieldnames)
        for data in csv_data:
            writer.writerow(data)
